<template>
	<view class="py-10 inl-block" @click="viewFile">
		<view class="text-primary inl-block primary">{{fileName}}</view>
	</view>
</template>

<script>
	import $U from '@/common/lib/util.js'
	export default {
		props: {
			filePath: {
				type: String,
				default: ''
			},
			fileName: {
				type: String,
				default: ''
			}
		},
		computed: {
			isImage() {
				let type = $U.getFileExtension(this.filePath)
				let pattern = /(jpeg|jpg|png|gif)$/i;
				return pattern.test(type)
			},
			isDocument() {
				let type = $U.getFileExtension(this.filePath)
				let pattern = /(doc|xls|txt|ppt|pdf|docx|xlsx|pptx)$/i;
				return pattern.test(type)
			}
		},
		methods: {
			viewFile() {
				if (this.isImage) {
					uni.previewImage({
						urls: [this.filePath]
					})
				} else if (this.isDocument) {
					this.viewDocument();
				}
			},
			viewDocument() {
				console.log('文件预览1')

				// #ifdef MP-WEIXIN
				// 小程序用 uni.openDocument
				uni.downloadFile({
					url: this.filePath,
					success: function(res) {
						var filePath = res.tempFilePath;
						uni.openDocument({
							filePath: filePath,
							showMenu: true,
							success: function(res) {
								// console.log('打开文档成功');
							}
						});
					}
				});
				// #endif

				// #ifdef H5
				// 公众号用 待解决
				if (this.filePath) {
					let link = document.createElement('a');
					link.href = this.filePath;
					// link.download = 'example.pdf'; // 设置下载文件名
					document.body.appendChild(link);
					link.click();
					document.body.removeChild(link);
				}
				// #endif



			}
		},
	}
</script>

<style scoped>
	.inl-block {
		display: inline-block;
	}

	.primary {
		width: 100%;
		/* 确保元素占据整个宽度 */
		word-break: break-all;
		/* 强制文本换行 */
		white-space: normal;
		/* 允许文本正常换行 */
		overflow: hidden;
		/* 隐藏溢出的内容 */
	}
</style>